package com.luoxiang.socialandroid.activity;

import static android.animation.ValueAnimator.REVERSE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.IMTOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME;

import android.Manifest;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.LoginBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.dialog.LoginServiceTipDialog;
import com.luoxiang.socialandroid.dialog.PrivacyDialog;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.LogUtils;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.StatusBarFontUtil;
import com.lxj.xpopup.XPopup;
import com.netease.nis.quicklogin.QuickLogin;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class LoginActivity extends BaseActivity {
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private ScrollView mScrollView;
    private RelativeLayout mLayout;
    private Button btn_login;
    private TextView loginbycode;
    //    private PhoneNumberAuthHelper mAlicomAuthHelper;
//    private TokenResultListener mTokenListener;
    private ProgressDialog mProgressDialog;
    private TextView mTvResult;
    private int mUIType;
    private String secretInfo;
    private String token;
    private TextView im_login_agreement;
    private ImageView select_false;
    private Boolean isSelect = false;
    public static HomeActivity instance;
    private TextView login_yonghu, login_yinsi;
    public static LoginActivity logininstance;
    private TextView tvLianxikf;

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        setStatusBarTranslucent();
        isShowGift = false;
        logininstance = this;
    }

    @Override
    protected void initView() {
        select_false = findViewById(R.id.select_false);
        mScrollView = findViewById(R.id.mScrollView);
        tvLianxikf = findViewById(R.id.tvLianxikf);
        mLayout = (RelativeLayout) findViewById(R.id.mLayout);
        btn_login = findViewById(R.id.btn_login);
        loginbycode = findViewById(R.id.loginbycode);
        login_yinsi = findViewById(R.id.login_yinsi);
        im_login_agreement = (TextView) findViewById(R.id.im_login_agreement);
        login_yonghu = findViewById(R.id.login_yonghu);
        initScreenRecorderBuild();//请求权限的方法
        StatusBarFontUtil.setLightStatusBarColor(this);
        secretInfo = "CRaMnU7MtWtvEoJyirXaP04U0rRy6rZhVQMI5znNPnrnOPKE/PQPBG36dMOmbKSx6/tdIksq5yC4Rm+cwC2dNxZYhw3/oNOzIJaHrWQDt1TRHD12H0K5yxTrf18ZwnYMxSEwXrEafJ6YbwwOiCpaEB/hgiW7tRfYCF+CE3ylE4t6pva4yJwAfLfqwTAVFYM+Irx4khcfXp7MYQsAsE3qRoEVd6GAQnYHJU6chiV+P6y7qHPV1zg/sD9Q/x7rPYbyo9dki/q2ALgdQ7kR5Ug9BBEb8re3CZdlSO+dU6wKuuanImffo9lvuhG4TaISyUSb";
//添加权限检查
//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
//            return;
//        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AppUtils.exitApp();
    }

    @Override
    protected void initListener() {
        mScrollView.post(new Runnable() {
            @Override
            public void run() {
                ValueAnimator animator = (ValueAnimator) ValueAnimator.ofInt(0, mScrollView.getChildAt(0).getMeasuredHeight());
                animator.setDuration(30000);
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int mFloat = (int) animation.getAnimatedValue();
                        mScrollView.scrollTo(0, mFloat);
                    }
                });
                animator.setRepeatCount(50);
                animator.setRepeatMode(REVERSE);
                animator.start();
            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelect) {
                    Intent intent = new Intent(LoginActivity.this, LoginbyCodeActivity.class);
                    startActivity(intent);
                } else {
                    PrivacyDialog privacyDialog = new PrivacyDialog(LoginActivity.this);
                    privacyDialog.setOnConfirmClickListener(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            Intent intent = new Intent(LoginActivity.this, LoginbyCodeActivity.class);
                            startActivity(intent);
                            privacyDialog.dismiss();
                            return null;
                        }
                    });
                    privacyDialog.setOnCancleClickListener(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            privacyDialog.dismiss();
                            return null;
                        }
                    });
                    new XPopup.Builder(LoginActivity.this)
                            .asCustom(privacyDialog)
                            .show();
                }
            }
        });
        login_yinsi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, AgreementActivity.class);
                startActivity(intent);

            }
        });
        login_yonghu.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(LoginActivity.this, WebloadActivity.class);
                intent.putExtra("title", getString(R.string.mi_yonghuxieyi));
                intent.putExtra("webUrl", "http://mlhtml-test.dhxwlkj.com/userAgreement/index.html");
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        select_false.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelect) {
                    isSelect = false;
                    select_false.setImageResource(R.mipmap.icon_selectfalse);
                } else {
                    isSelect = true;
                    select_false.setImageResource(R.mipmap.yijinggouxuan);
                }
            }
        });
        tvLianxikf.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                new XPopup.Builder(LoginActivity.this)
                        .asCustom(new LoginServiceTipDialog(LoginActivity.this))
                        .show();
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    private void descrype() {
        String key = "a5uJAS8HNqxWbvDdnA2fNtlW3vz7LOMb";
        String encryptStr = null;
        try {
            encryptStr = AESUtil.aesEncryptString("{\"code\":1,\"msg\":\"验证码错误\",\"data\":null}", key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(encryptStr);
        String decryptStr = null;
        try {
            decryptStr = AESUtil.aesDecryptString(encryptStr, key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.d("decryptStr", decryptStr);
        LogUtils.d("encryptStr", encryptStr);
    }

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CHANGE_WIFI_STATE


        ).subscribe(aBoolean -> {
            if (aBoolean) {

            } else {
            }
        });
    }

    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }


    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    /**
     * @param type
     * @param extra
     * @param accessToken 一键登录请求接口
     */
    private void getloginbykey(Activity activity, Integer type, String extra, String accessToken, String yiToken) {
        getRequest();
        NetUtils.getInstance().getApiService().getloginbykey(type, extra, accessToken, yiToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        if (numberBean != null) {
                            String data = numberBean.getData();
                            String decryptStr = null;
                            try {
                                decryptStr = AESUtil.aesDecryptString(data, KEY);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            com.blankj.utilcode.util.LogUtils.i("decryptStrs", decryptStr);
                            Gson gson = new Gson();
                            LoginBean loginkeyBean = gson.fromJson(decryptStr, LoginBean.class);
                            if (loginkeyBean != null) {
                                if (loginkeyBean.getData() != null) {
                                    if (loginkeyBean.getData().getUser() != null) {
                                        MmkvUtil.INSTANCE.encode("phone", loginkeyBean.getData().getThirdId());
                                        MmkvUtil.INSTANCE.encode(TOKEN, loginkeyBean.getData().getUser().getToken().toString());
                                        MmkvUtil.INSTANCE.encode(HOSTAUDIT, loginkeyBean.getData().getUser().getHost());
                                        MmkvUtil.INSTANCE.encode(GENDER, loginkeyBean.getData().getUser().getGender());
                                    }
                                }
                            }
                            if (loginkeyBean != null) {
                                if (loginkeyBean.getData() != null) {
                                    if (loginkeyBean.getData().getUser() != null) {
                                        MmkvUtil.INSTANCE.encode("phone", loginkeyBean.getData().getThirdId());
                                        MmkvUtil.INSTANCE.encode(IMTOKEN, loginkeyBean.getData().getUser().getImToken());
                                        MmkvUtil.INSTANCE.encode(ACCID, loginkeyBean.getData().getUser().getId());
                                        MmkvUtil.INSTANCE.encode(USERID, loginkeyBean.getData().getUser().getId());
                                        MmkvUtil.INSTANCE.encode(USER_NAME, loginkeyBean.getData().getUser().getName());
                                    }
                                }
                                if (loginkeyBean.getCode() == 0) {
                                    QuickLogin quickLogin = QuickLogin.getInstance();
                                    if (loginkeyBean.getData().getUser() != null) {
                                        if (loginkeyBean.getData().getTrait()) {
                                            MmkvUtil.INSTANCE.encode("keybutezhi", "ok");
                                            MmkvUtil.INSTANCE.encode(IMTOKEN, loginkeyBean.getData().getUser().getImToken());
                                            MmkvUtil.INSTANCE.encode(ACCID, loginkeyBean.getData().getUser().getId());
                                            MmkvUtil.INSTANCE.encode(USERID, loginkeyBean.getData().getUser().getId());
                                            Intent intent = new Intent(activity, HomeActivity.class);
                                            activity.startActivity(intent);
                                            quickLogin.quitActivity();
                                        } else {
                                            MmkvUtil.INSTANCE.encode("keybutezhi", "");
                                            MmkvUtil.INSTANCE.encode(IMTOKEN, loginkeyBean.getData().getUser().getImToken());
                                            MmkvUtil.INSTANCE.encode(ACCID, loginkeyBean.getData().getUser().getId());
                                            MmkvUtil.INSTANCE.encode(USERID, loginkeyBean.getData().getUser().getId());
                                            Intent intent = new Intent(activity, Tezhi1Activity.class);
                                            activity.startActivity(intent);
                                            quickLogin.quitActivity();
                                        }
                                    } else {
                                        MmkvUtil.INSTANCE.encode("phone", loginkeyBean.getData().getThirdId());
                                        Intent intent = new Intent(activity, RegisterActivity.class);
                                        activity.startActivity(intent);
                                        quickLogin.quitActivity();
                                    }
                                } else {
                                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.mi_denglushibai);
                                }
                            }
                        } else {
                            com.blankj.utilcode.util.ToastUtils.showShort(R.string.mi_houduanweifanweishiju);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 请求头传参方式
     */
    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}